﻿using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace XKPlatform.Filter
{
    public class StaticFileAuthMiddleWare
    {
        private readonly RequestDelegate _next;//下一个中间件


        public StaticFileAuthMiddleWare(RequestDelegate next)
        {
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            this._next = next;
            // _logger = loggerFactory.CreateLogger<CalculateExecutionTimeMiddleware>();
        }

        public async Task Invoke(HttpContext context)
        {
            var path = context.Request.Path.Value;
            if (path.Contains(".js") || path.Contains(".json"))
            {
                if (context.Request.Headers["Referer"].Count == 0 || !context.Request.Headers["Referer"][0].Contains("/views/index.html"))
                {
                    Console.WriteLine("=====js no=======" + "|path=" + path);

                    context.Response.StatusCode = 403; //(int)httpStatusEnum.;
                    await context.Response.WriteJsonAsync(JsonConvert.SerializeObject(new { code = 403, msg = "没有权限访问" }));
                    return;
                }

            }
            await _next.Invoke(context);
        }
    }
}
